package com.guyu.plugin.mybatis.config;

import com.guyu.common.web.factory.YmlPropertySourceFactory;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.query.QueryColumnBehavior;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * mybatis-flex配置类(下方注释有插件介绍)
 *
 * @author yhan219
 */
@Slf4j(topic = "sql")
@EnableTransactionManagement(proxyTargetClass = true)
@AutoConfiguration
@MapperScan("${mybatis-flex.mapper-packages}")
@PropertySource(value = "classpath:common-mybatis.yml", factory = YmlPropertySourceFactory.class)
public class MybatisFlexConfig implements MyBatisFlexCustomizer {


    static {
//        QueryColumnBehavior.setIgnoreFunction(QueryColumnBehavior.IGNORE_BLANK);
        QueryColumnBehavior.setSmartConvertInToEquals(true);
    }

    @Value("${mybatis-flex.configuration.audit_enable}")
    private Boolean enableAudit = false;
    @Value("${mybatis-flex.configuration.sql_print}")
    private Boolean sqlPrint = false;

    @Override
    public void customize(FlexGlobalConfig globalConfig) {
        //开启审计功能
        AuditManager.setAuditEnable(enableAudit);
        // 开启sql打印默认会开启sql审计
        if (sqlPrint) {
            AuditManager.setAuditEnable(true);
            //设置 SQL 审计收集器
            AuditManager.setMessageCollector(auditMessage -> {
                        Long tookTimeMillis = auditMessage.getElapsedTime();
                        String sql = auditMessage.getFullSql();
                        if (tookTimeMillis > 200) {
                            log.warn("Slow sql exec took {} ms >>> {}", tookTimeMillis, sql);
                        } else {
                            log.info("Flex exec sql took {} ms >>> {}", tookTimeMillis, sql);
                        }
                    }
            );
        }
    }

}
